import { onMounted, ref, nextTick } from "vue";
import type { Ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getProduceDetail } from "../api/api";
import { Toast, ImagePreview } from "vant";

interface IAPIProduct {
  code: string;
  data: IProductItem;
  message: string;
}
interface IProductItem {
  originprice?: string;
  proname?: string;
  banners: string[];
}
interface IVideo {
  play: () => void;
  sum: () => number;
}


export const useAPIProductDetail = () => {
  const productSwiper: Ref<string[]> = ref([]);
  const showPopover: Ref<boolean> = ref(false);
  const actions = [
    { text: "首页", icon: "home-o", path: "/home" },
    { text: "购物车", icon: "cart-o", path: "/car" },
    { text: "分享", icon: "share-o" },
  ];
  const showShare = ref(false);
  const options = [
    { name: "微信", icon: "wechat" },
    { name: "微博", icon: "weibo" },
    { name: "复制链接", icon: "link" },
    { name: "分享海报", icon: "poster" },
    { name: "二维码", icon: "qrcode" },
  ];
  const route = useRoute();
  const router = useRouter();
  const productId: Ref<string> = ref("");
  const videoShow = ref(false);
  const refVideo: Ref<IVideo | null> = ref(null);
  const productContent: Ref<IProductItem> = ref({ banners: [] });
  const APIProductDetail = async (id: string) => {
    const res = (await getProduceDetail(id)) as unknown as IAPIProduct;
    if (res.code === "200") {
      productContent.value = res.data;
      productSwiper.value = res.data.banners[0].split(",");
    }
  };
  // console.log(productContent);
  const selectPopItem = (actions: { text: string; index: number }) => {
    if (actions.text === "首页") {
      router.push("/");
    } else if (actions.text === "购物车") {
      router.push("/car");
    } else if (actions.text === "分享") {
      showShare.value = true;
    }
  };

  const shareSelect = (option: { name: string; icon: string }) => {
    new Toast(option.name);
    // 调用和微博微信相关的JSapi
    showShare.value = false;
  };

  const selctPicItem = (index: number) => {
    new ImagePreview({
      images: productSwiper.value,
      startPosition: index,
    });
  };

  const playVideo = () => {
    videoShow.value = true;
    nextTick(() => {
      refVideo.value?.play();
    });
  };

  const addCarList =()=>{
    
  }
  onMounted(() => {
    productId.value = route?.query?.id as string;
    APIProductDetail(productId.value);
  });

  return {
    showPopover,
    actions,
    selectPopItem,
    showShare,
    options,
    shareSelect,
    productSwiper,
    selctPicItem,
    playVideo,
    productContent,
    videoShow,
    addCarList
  };
};
